#! /bin/sh
# Create deconvolution test panels for an input cmp gather
# Authors: Jack, Ken
# NOTE: Comment lines preceeding user input start with  #!#
#set -x

#!# Set file etc.
input=cdpby100
cdp=501		# pick a cdp -- also used for naming output files
fold=30
space=6		# 6 null traces between panels
tpow=2		# gain power before deconvolutions and autocorrelations

#!# Determine range of decon parameters
gapmin=8 gapmax=32 dgap=8 # use milliseconds to run loop
j=0  # test panel number
len=.128 dlen=0 tmin=2.0 tmax=4.0 expand=1.5


### Determine ns, nf and dt from data (for sunull)
nt=`sugethw ns <$input | sed 1q | sed 's/.*ns=//'`
dt=`sugethw dt <$input | sed 1q | sed 's/.*dt=//'`

### Convert dt to seconds from header value in microseconds
dt=`bc -l <<-END
	$dt / 1000000
END`
nf=`suwind count=1 <$input | suacor | sugethw ns | sed 1q | sed 's/.*ns=//'`


### Label output according to cdp number and get the cdp
deconpanel=decon.$cdp
autocorpanel=autocor.$cdp
deconparams=deconparams.$cdp
suwind <$input key=cdp min=$cdp max=$cdp count=$fold >cdp.$cdp


# Loop over deconvolution parameters
>$deconpanel  # zero output files
>$autocorpanel
>temp

cp cdp.$cdp $deconpanel  # zeroth panels are w/o decon
sugain <cdp.$cdp tpow=$tpow | suacor norm=1 >>$autocorpanel  
sunull ntr=$space nt=$nt dt=$dt >>$deconpanel
sunull ntr=$space nt=$nf dt=$dt >>$autocorpanel

echo "Test minlag maxlag tmin tmax" >$deconparams
gap=$gapmin
while [ $gap -le $gapmax ]
do
	j=`bc -l <<-END
		$j + 1
	END`
	minlag=`bc -l <<-END
		scale=5; $gap / 1000
	END`
	maxlag=`bc -l <<-END
		scale=5; $minlag + $len
	END`

	sugain <cdp.$cdp tpow=$tpow |
	supef minlag=$minlag maxlag=$maxlag mincorr=$tmin maxcorr=$tmax |
	tee temp  >>$deconpanel
	sunull ntr=$space nt=$nt dt=$dt >>$deconpanel
	sugain <temp tpow=$tpow | suacor norm=1 >>$autocorpanel
	sunull ntr=$space nt=$nf dt=$dt >>$autocorpanel
	rm temp

	echo "$j   $minlag $maxlag $tmin $tmax" >>$deconparams
	gap=`bc <<-END
		$gap + $dgap
	END`
	dgap=`bc -l <<-END
		$expand * $dgap
	END`
	dlen=`bc -l <<-END
		$expand * $dlen
	END`
	len=`bc -l <<-END
		$len + $dlen
	END`
done


echo "The parameter values are recorded in $deconparams"

### Plot deconvolution test panels
f2=0
d2=`bc -l <<-END
	1/($fold + $space)
END`

sugain <$deconpanel gpow=.5 |
suxwigb f2=$f2 d2=$d2 perc=99 title="File: $input  Deconvolution Test"  \
	label1="Time (s)"  label2="Deconvolution Test Number" & 

sugain <$autocorpanel gpow=.5 |
suxwigb f2=$f2 d2=$d2 perc=99 title="File: $input  Autocorrelations"  \
	label1="Time (s)"  label2="Deconvolution Test Number" & 
